package com.stox.core.event;

import java.util.ArrayList;
import java.util.List;

public final class ApplicationEventPublisher {
	
	private static List<ApplicationEventListener> listeners= new ArrayList<ApplicationEventListener>();
	private static List<ApplicationEventListener> pendingSubscribers = new ArrayList<ApplicationEventListener>();
	
	public static void publish(ApplicationEvent event){
		for(ApplicationEventListener pendingSubscriber : pendingSubscribers){
			if(!listeners.contains(pendingSubscriber)){
				listeners.add(pendingSubscriber);
			}
		}
		pendingSubscribers.clear();
		for(ApplicationEventListener listener : listeners){
			if(listener.supports(event.getClass())){
				listener.onApplicationEvent(event);
			}
		}
	}
	
	public static void subscribe(ApplicationEventListener listener){
		if(!listeners.contains(listener)){
			pendingSubscribers.add(listener);
		}
	}
	
}
